package com.csp.mingyue.oss.controller;

import cn.hutool.core.util.ObjectUtil;
import com.csp.mingyue.common.core.vo.R;
import com.csp.mingyue.oss.api.vo.SysOssVo;
import com.csp.mingyue.oss.service.SysOssService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.List;

/**
 * 对象存储服务
 *
 * @author njy
 * @since 2023-09-12 09:19:12
 */
@Slf4j
@Tag(name = "对象存储服务")
@RestController
@RequestMapping("/sysOss")
@RequiredArgsConstructor
public class SysOssController {

	private final SysOssService sysOssService;

	@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@Operation(summary = "上传文件")
	public R<SysOssVo> upload(@RequestPart("file") MultipartFile file) {
		if (ObjectUtil.isNull(file)) {
			return R.fail("上传文件不能为空");
		}

		return R.ok(sysOssService.upload(file));
	}

	@DeleteMapping("/{ossIds}")
	@Operation(summary = "删除OSS对象存储", parameters = {
			@Parameter(in = ParameterIn.PATH, name = "ossIds", description = "oss对象Ids", required = true) })
	public R<Boolean> remove(@NotEmpty(message = "主键不能为空") @PathVariable List<Long> ossIds) {
		return R.ok(sysOssService.deleteByOssIds(ossIds));
	}

	@GetMapping("/download/{ossId}")
	@Operation(summary = "下载OSS对象存储", parameters = {
			@Parameter(in = ParameterIn.PATH, name = "ossIds", description = "oss对象Ids", required = true) })
	public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
		sysOssService.download(ossId, response);
	}

}
